//
//  Register2VC.m
//  phmall
//
//  Created by admin on 2017/9/21.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "Register2VC.h"
#import "RegionViewController.h"
@interface Register2VC ()<RegionViewControllerDelegate>{
    UITextField *phone;
    UITextField *code;
    NSInteger   count;
    UIButton    *send;
    UIButton    *area;
}
@property(nonatomic,strong)SocketIOClient *client;
@property(nonatomic,strong)NSTimer *timer;
@end

@implementation Register2VC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self connection];
    self.view.backgroundColor=[UIColor whiteColor];
    if ([self.type isEqualToString:@"new"]) {
        self.title=Localized(@"新用户注册");
    }
    if ([self.type isEqualToString:@"google"]) {
        self.title=@"绑定google账号";
    }
    if ([self.type isEqualToString:@"facebook"]) {
        self.title=@"绑定facebook账号";
    }
    [self setUI];
    // Do any additional setup after loading the view.
}
- (void)connection{
    
    [self.client on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
        NSLog(@"*************\n\niOS客户端上线\n\n*************");
    }];
    [self.client on:@"check_phone" callback:^(NSArray * _Nonnull event, SocketAckEmitter * _Nonnull ack) {
        NSString *data=[NSString stringWithFormat:@"%@", event?event[0]:@""];
        if ([data isEqualToString:@"-9"]) {
            [PublicClass ProgressHUDModeText:@"发送成功" andTime:2];
        }else if([data isEqualToString:@"2"]){
            [PublicClass ProgressHUDModeText:@"手机号码已被注册" andTime:2];
            send.userInteractionEnabled=YES;
            [send setTitle:@"获取验证码" forState:UIControlStateNormal];
            send.userInteractionEnabled=YES;
            [self.timer invalidate];
            self.timer=nil;
        }else if([data isEqualToString:@"1"]){
            [PublicClass ProgressHUDModeText:@"发送失败" andTime:2];
            send.userInteractionEnabled=YES;
            [send setTitle:@"获取验证码" forState:UIControlStateNormal];
            send.userInteractionEnabled=YES;
            [self.timer invalidate];
            self.timer=nil;
        }else{
            [PublicClass ProgressHUDModeText:data andTime:2];
            send.userInteractionEnabled=YES;
            [send setTitle:@"获取验证码" forState:UIControlStateNormal];
            send.userInteractionEnabled=YES;
            [self.timer invalidate];
            self.timer=nil;
        }
    }];
    [self.client on:@"error" callback:^(NSArray * _Nonnull event, SocketAckEmitter * _Nonnull ack) {
        [PublicClass ProgressHUDModeText:@"连接服务器失败，正在重新连接" andTime:2];
        send.userInteractionEnabled=YES;
        [self.timer invalidate];
        self.timer=nil;
    }];
    
    [self.client connect];
    
}
-(void)rightBarAction{
    
}

-(void)setUI{
    UIBarButtonItem *rightBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"帮助中心"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarAction)];
    self.navigationItem.rightBarButtonItem=rightBar;
    
    UIBarButtonItem *leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    
    UIImageView *logo=[[UIImageView alloc]init];
    [self.view addSubview:logo];
  
    logo.image=[UIImage imageNamed:@"logo"];
    ViewBorderRadius(logo, 10, 0, [UIColor whiteColor]);
    [logo mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset((218-RectStatus.size.height-44-64));
        make.centerX.equalTo(self.view);
        make.width.height.offset(70);
    }];
    
    UILabel *name=[[UILabel alloc]init];
    [self.view addSubview:name];
    name.font=[UIFont systemFontOfSize:24];
    name.textColor=[UIColor colorWithHexString:@"#ff9300"];
    name.text=@"Hello,white";
    [name mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logo.mas_bottom).with.offset(20);
        make.centerX.equalTo(self.view);
    }];
    
    area=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:area];
//    area.textAlignment=NSTextAlignmentCenter;
    [area setTitle:@"+86" forState:UIControlStateNormal];
    [area setTitleColor:[UIColor colorWithHexString:@"#454545"] forState:UIControlStateNormal];
    area.titleLabel.font=[UIFont systemFontOfSize:18];
    [area addTarget:self action:@selector(chooseRegion) forControlEvents:UIControlEventTouchUpInside];
    [area mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(name.mas_bottom).with.offset(30);
        make.left.equalTo(self.view).with.offset(30);
        make.width.offset(70);
        make.height.offset(40);
    }];
    
    UIView *numLine=[[UILabel alloc]init];
    [self.view addSubview:numLine];
    numLine.backgroundColor=[UIColor orangeColor];
    [numLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(area.mas_bottom);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
        make.left.equalTo(self.view).with.offset(20);
        make.height.offset(1);
    }];
    
    UIView *endways=[[UILabel alloc]init];
    [self.view addSubview:endways];
    endways.backgroundColor=[UIColor orangeColor];
    [endways mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(area);
        make.width.offset(1);
        make.left.equalTo(area.mas_right).with.offset(10);
    }];
    
    phone=[[UITextField alloc]init];
    [self.view addSubview:phone];
    phone.placeholder=Localized(@"手机号");
    phone.font=[UIFont systemFontOfSize:18];
    [phone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(area);
        make.height.offset(40);
        make.left.equalTo(endways).with.offset(10);
        make.right.equalTo(self.view).with.offset(-30);
    }];
    
    code=[[UITextField alloc]init];
    [self.view addSubview:code];
    code.placeholder=Localized(@"验证码");
    code.font=[UIFont systemFontOfSize:18];
    [code mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(area.mas_bottom).with.offset(30);
        make.left.equalTo(self.view).with.offset(30);
        make.right.equalTo(self.view.mas_centerX).with.offset(-20);
        make.height.offset(40);
    }];
    
    UIView *codeLine=[[UILabel alloc]init];
    [self.view addSubview:codeLine];
    codeLine.backgroundColor=[UIColor orangeColor];
    [codeLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(code.mas_bottom);
        make.right.equalTo(self.view.mas_centerX).with.offset(-10);
        make.left.equalTo(self.view).with.offset(20);
        make.height.offset(1);
    }];
    
    send=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:send];
    [send setTitle:Localized(@"发送验证码") forState:UIControlStateNormal];
    [send setBackgroundImage:[UIImage imageNamed:@"发送验证码"] forState:UIControlStateNormal];
    [send addTarget:self action:@selector(sendAction) forControlEvents:UIControlEventTouchUpInside];
    [send setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    send.backgroundColor=[UIColor colorWithHexString:@"#ff9300"];
    ViewBorderRadius(send, 5, 0, [UIColor colorWithHexString:@"#ff9300"]);
    [send mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(code);
        make.left.equalTo(self.view.mas_centerX).with.offset(10);
        make.right.equalTo(self.view).with.offset(-20);
    }];
    
    UIButton *consent=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:consent];
    [consent setTitle:Localized(@"同意协议并注册") forState:UIControlStateNormal];
    [consent addTarget:self action:@selector(consentAction) forControlEvents:UIControlEventTouchUpInside];
    [consent setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    consent.backgroundColor=[UIColor colorWithHexString:@"#ff9300"];
//    ViewBorderRadius(consent, 5, 1, [UIColor colorWithHexString:@"#ff9300"]);
    [consent setBackgroundImage:[UIImage imageNamed:@"背景渐变条"] forState:UIControlStateNormal];
    [consent mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(code.mas_bottom).with.offset(50);
        make.height.offset(44);
        make.left.equalTo(self.view).with.offset(20);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
    }];
    
    UIButton *agreement=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:agreement];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"《%@》",Localized(@"菲淘网服务协议")]];
    
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#ff9300"]  range:strRange];
    [agreement setAttributedTitle:str forState:UIControlStateNormal];
    agreement.titleLabel.font=[UIFont systemFontOfSize:13];
    //    [consent addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [agreement mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(consent.mas_bottom).with.offset(50);
        make.centerX.equalTo(self.view);
    }];
}
-(void)chooseRegion{
    RegionViewController *region=[[RegionViewController alloc]init];
    region.delegate=self;
    [self.navigationController pushViewController:region animated:YES];
}
-(void)chooseRegion:(NSString *)region{
    [area setTitle:region forState:UIControlStateNormal];
}
-(void)consentAction{

    if (phone.text.length==0||phone.text==nil) {
         [PublicClass ProgressHUDModeText:@"手机号不可为空" andTime:2];
//        [SVProgressHUD showErrorWithStatus:@"手机号不可为空"];
        return;
    }
    if (code.text.length==0||code.text==nil) {
//        [SVProgressHUD showErrorWithStatus:@"验证码不可为空"];
        [PublicClass ProgressHUDModeText:@"验证码错误" andTime:2];
        return;
    }
    [self loadDataWithregister];
}
-(void)sendAction{
    NSString *code=[[NSString alloc]init];
    if (phone.text.length==0||phone.text==nil) {
       [PublicClass ProgressHUDModeText:@"手机号不可为空" andTime:2];
        return;
    }
    if ([area.titleLabel.text isEqualToString:@"+63"]) {
        if ([phone.text hasPrefix:@"0"]) {
            code=[NSString stringWithFormat:@"63%@",phone.text];
        }else{
            code=[NSString stringWithFormat:@"630%@",phone.text];
        }


        if (!([phone.text hasPrefix:@"9"]||[phone.text hasPrefix:@"09"])) {
            [PublicClass ProgressHUDModeText:@"手机号格式错误" andTime:2];
            return;
        }
        NSString *userNameRegex = @"[0-9]{13}$";
        NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
        if (![userNamePredicate evaluateWithObject:code]) {
            [PublicClass ProgressHUDModeText:@"手机号格式错误" andTime:2];
            return;
        }
    }else{
        code=[NSString stringWithFormat:@"86%@",phone.text];
        NSString *userNameRegex = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
        NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
        if (![userNamePredicate evaluateWithObject:phone.text]) {
            [PublicClass ProgressHUDModeText:@"手机号格式错误" andTime:2];
            return;
        }
    }

    send.userInteractionEnabled=NO;
    [self timeFailBeginFrom:60];
    [self.client emit:@"check_phone" with:@[code]];
}
- (void)timeFailBeginFrom:(NSInteger)timeCount {

    count = timeCount;
//    self.enabled = NO;
    // 加1个计时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}
- (void)timerFired {
    if (count != 0) {
        count -= 1;
        NSLog(@"%ld",(long)count);
        [send setTitle:[NSString stringWithFormat:@"%ld", (long)count] forState:UIControlStateNormal];
    } else {
        send.userInteractionEnabled=YES;
        [send setTitle:@"获取验证码" forState:UIControlStateNormal];
//        count = 60;
        [self.timer invalidate];
        self.timer=nil;
    }
}
- (void)loadDataWithregister{
    NSString *number=phone.text;
    if ([number hasPrefix:@"9"]) {
        number =[NSString stringWithFormat:@"0%@",number];
    }
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"register"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    if ([self.type isEqualToString:@"new"]) {
        [parametersDic setValue:self.name forKey:@"login_id"];
        [parametersDic setValue:self.pass forKey:@"pass1"];
        [parametersDic setValue:number forKey:@"member_tel11"];
        [parametersDic setValue:code.text forKey:@"code"];
    }
    if ([self.type isEqualToString:@"google"]) {
        [parametersDic setValue:self.name forKey:@"login_id"];
        [parametersDic setValue:self.pass forKey:@"pass1"];
        [parametersDic setValue:number forKey:@"member_tel11"];
        [parametersDic setValue:code.text  forKey:@"code"];
        [parametersDic setValue:[GIDSignIn sharedInstance].currentUser.userID forKey:@"oauth_uid"];
        [parametersDic setValue:[GIDSignIn sharedInstance].currentUser.authentication.idToken forKey:@"token"];
        [parametersDic setValue:self.type forKey:@"type"];
    }
    if ([self.type isEqualToString:@"facebook"]) {
        [parametersDic setValue:self.name forKey:@"login_id"];
        [parametersDic setValue:self.pass forKey:@"pass1"];
        [parametersDic setValue:number forKey:@"member_tel11"];
        [parametersDic setValue:code.text  forKey:@"code"];
        [parametersDic setValue:[FBSDKAccessToken currentAccessToken].userID forKey:@"oauth_uid"];
        [parametersDic setValue:[FBSDKAccessToken currentAccessToken].tokenString  forKey:@"token"];
        [parametersDic setValue:self.type forKey:@"type"];
    }
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",responseDict);
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            [PublicClass ProgressHUDModeText:Localized(@"登录成功") andTime:2];
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:[NSNumber numberWithBool:YES]];
                [self dismissViewControllerAnimated:YES completion:nil];
            });
        }else{
            [PublicClass ProgressHUDModeText:responseDict[@"data"] andTime:2];
        }
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
    }];
    
}
- (SocketIOClient *)client{
    if (!_client) {
        NSURL* url = [[NSURL alloc] initWithString:HomeURL];
        _client = [[SocketIOClient alloc] initWithSocketURL:url config:@{@"log": @YES, @"forcePolling": @YES}];
    }
    return _client;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
    [self.client disconnect];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
